package com.jogern.baselibrary;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.support.v4.app.FragmentActivity;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by jogern on 2016/8/15 0015.
 */

public class Manager {
    private static LinkedList<FragmentActivity> sActivities = new LinkedList<>();

    private static LinkedHashMap<String, Service> sServiceMap = new LinkedHashMap<>();

    public static void addCurrentActivity(FragmentActivity activity) {
        sActivities.add(activity);
    }

    public static Activity getCurrentActivity() {
        return sActivities.pollLast();
    }

    public static void removeCurrentActivity(FragmentActivity activity) {
        if (sActivities.contains(activity)) {
            sActivities.remove(activity);
        }
    }

    public static void addService(Service service) {
        sServiceMap.put(service.getClass().getName(), service);
    }

    public static void removeService(Service service) {
        String key = service.getClass().getName();
        if (sServiceMap.containsKey(key)) {
            sServiceMap.remove(key);
        }
    }

    public static boolean isServiceRunning(Context context, Class<? extends Service> cls) {
        if (cls != null) {
            final String key = cls.getName();
            if (sServiceMap.containsKey(key)) {
                return true;
            }
            ActivityManager activityManager = (ActivityManager)
                    context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(500);
            int size = null == serviceList ? 0 : serviceList.size();
            for (int i = 0; i < size; i++) {
                String name = serviceList.get(i).service.getClassName();
                if (name.equals(key)) {
                    return true;
                }
            }
        }
        return false;
    }
}
